package com.xyht.medicine_management_system.modules.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ExceptionCast;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.modules.addresses.entity.MmsAddresses;
import com.xyht.medicine_management_system.modules.consumptionPoint.constant.ConsumptionPointRecordConstant;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.MmsConsumptionPointRecord;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.MmsUserConsumptionPoint;
import com.xyht.medicine_management_system.modules.consumptionPoint.mapper.MmsConsumptionPointRecordMapper;
import com.xyht.medicine_management_system.modules.consumptionPoint.mapper.MmsUserConsumptionPointMapper;
import com.xyht.medicine_management_system.modules.coupon.constant.UserCouponRelationConstant;
import com.xyht.medicine_management_system.modules.coupon.entity.MmsUserCouponRelation;
import com.xyht.medicine_management_system.modules.coupon.entity.resp.MmsUserCouponRelationResp;
import com.xyht.medicine_management_system.modules.coupon.service.MmsUserCouponRelationService;
import com.xyht.medicine_management_system.modules.order.constant.OrderConstant;
import com.xyht.medicine_management_system.modules.order.constant.OrderMedicineInfoConstant;
import com.xyht.medicine_management_system.modules.order.constant.OrderRefundConstant;
import com.xyht.medicine_management_system.modules.order.entity.MmsOrder;
import com.xyht.medicine_management_system.modules.order.entity.MmsOrderMedicineInfo;
import com.xyht.medicine_management_system.modules.order.entity.MmsOrderRefund;
import com.xyht.medicine_management_system.modules.order.entity.req.MmsOrderRefundReq;
import com.xyht.medicine_management_system.modules.order.entity.resp.MmsOrderRefundResp;
import com.xyht.medicine_management_system.modules.order.entity.resp.MmsOrderResp;
import com.xyht.medicine_management_system.modules.order.entity.resp.OrderMedicineInfoResp;
import com.xyht.medicine_management_system.modules.order.mapper.MmsOrderMapper;
import com.xyht.medicine_management_system.modules.order.mapper.MmsOrderMedicineInfoMapper;
import com.xyht.medicine_management_system.modules.order.mapper.MmsOrderRefundMapper;
import com.xyht.medicine_management_system.modules.order.service.MmsOrderRefundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.medicine_management_system.modules.payment.alipay.util.AliPayUtil;
import com.xyht.medicine_management_system.modules.payment.entity.RefundResponse;
import com.xyht.medicine_management_system.modules.payment.util.PaymentUtil;
import com.xyht.medicine_management_system.modules.payment.wxpay.entity.RefundReq;
import com.xyht.medicine_management_system.modules.payment.wxpay.util.WxPayUtil;
import com.xyht.medicine_management_system.modules.user.entity.MmsUser;
import com.xyht.medicine_management_system.modules.user.entity.resp.MmsUserResp;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.medicine_management_system.common.util.ParamCheckUtil.isNullOrEmpty;

/**
 * <p>
 * 订单退款表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-12-14
 */
@Service
public class MmsOrderRefundServiceImpl extends ServiceImpl<MmsOrderRefundMapper, MmsOrderRefund> implements MmsOrderRefundService {
    @Resource
    private MmsOrderMapper mmsOrderMapper;
    @Resource
    private MmsUserMapper mmsUserMapper;
    @Resource
    private MmsUserCouponRelationService mmsUserCouponRelationService;
    @Resource
    private PaymentUtil paymentUtil;
    @Resource
    private MmsOrderMedicineInfoMapper mmsOrderMedicineInfoMapper;
    @Resource
    private MmsConsumptionPointRecordMapper mmsConsumptionPointRecordMapper;
    @Resource
    private MmsUserConsumptionPointMapper mmsUserConsumptionPointMapper;

    @Override
    @Transactional
    public ResponseResult submitRefund(MmsOrderRefundReq refundReq, String userId) {
        MmsOrder order = mmsOrderMapper.selectById(refundReq.getOrderId());
        if (order == null) { // 订单不存在
            return CommonResult.failed(CommonCodeEnum.ORDER_NOT_EXIST);
        }
        // 未查询到订单支付数据
        if (isNullOrEmpty(order.getPaymentAmount())) {
            return CommonResult.failed(CommonCodeEnum.ORDER_PAYMENT_AMOUNT_MISS);
        }
        // 非本人订单不可发起退款
        if (!order.getUserId().equals(userId)) {
            return CommonResult.failed(CommonCodeEnum.ORDER_NOT_OWNER);
        }
        // 订单非 待发货、待收货、已收货 状态不可退款
        if (order.getOrderStatus() != OrderConstant.ORDER_STATUS_TO_BE_DELIVERED &&
                order.getOrderStatus() != OrderConstant.ORDER_STATUS_TO_BE_RECEIVED &&
                order.getOrderStatus() != OrderConstant.ORDER_STATUS_ALREADY_RECEIVED) {
            return CommonResult.failed(CommonCodeEnum.ORDER_CAN_NOT_REFUND);
        }
        // 校验订单是否结束
        if (order.getIsClose()) {
            return CommonResult.failed(CommonCodeEnum.ORDER_IS_CLOSED);
        }

        // 新增退款记录
        MmsOrderRefund orderRefund = new MmsOrderRefund();
        BeanUtils.copyProperties(refundReq, orderRefund, "id");
        orderRefund.setUserId(userId);
        orderRefund.setMedicineInfo(order.getMedicineInfo()); // 药品信息
        orderRefund.setStatus(OrderRefundConstant.ORDER_REFUND_STATUS_TO_BE_REFUNDED); // 待退款
        // 设置退款流程
        orderRefund.setProcessApprovalStatus(OrderRefundConstant.ORDER_REFUND_PROCESS_STATUS_NO_APPROVAL); // 待审批
        boolean saveSuccess = this.save(orderRefund);
        if (!saveSuccess) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        // 修改订单状态 及 退款记录
        if (order.getIsRefund() == OrderConstant.ORDER_IS_REFUND_NO) { // 不存在售后
            order.setIsRefund(OrderConstant.ORDER_IS_REFUND_YES); // 设置为存在售后
            order.setIsRefunding(true); // 在售后中
            order.setRefundIdList(JSON.toJSONString(Collections.singletonList(refundReq.getId())));
        } else { // 存在售后
            List<String> refundIdList = JSON.parseArray(order.getRefundIdList(), String.class);
            refundIdList.add(orderRefund.getId());
            order.setRefundIdList(JSON.toJSONString(refundIdList));
        }
        int updNum = mmsOrderMapper.updateById(order);
        if (updNum != 1) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        return CommonResult.success(orderRefund.getId());
    }

    @Override
    @Transactional
    public ResponseResult agreeRefund(MmsOrderRefundReq refundReq, String userId) {
        if (isNullOrEmpty(refundReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        // 查询订单退款记录
        MmsOrderRefund orderRefund = this.getById(refundReq.getId());
        if (orderRefund == null) {
            return CommonResult.failed(CommonCodeEnum.ORDER_REFUND_NOT_EXIST);
        }
        // 非待退款状态不可同意退款
        if (orderRefund.getStatus() != OrderRefundConstant.ORDER_REFUND_STATUS_TO_BE_REFUNDED) {
            return CommonResult.failed(CommonCodeEnum.ORDER_CAN_NOT_REFUND);
        }

        // 查询订单数据
        MmsOrder order = mmsOrderMapper.selectById(orderRefund.getOrderId());
        if (order == null) { // 订单不存在
            return CommonResult.failed(CommonCodeEnum.ORDER_NOT_EXIST);
        }
        // 未查询到订单支付数据
        if (isNullOrEmpty(order.getPaymentAmount(), order.getPaymentTransactionId())) {
            return CommonResult.failed(CommonCodeEnum.ORDER_PAYMENT_AMOUNT_MISS);
        }
        // 订单非 待发货、待收货、已收货 状态不可进行退款相关操作
        if (order.getOrderStatus() != OrderConstant.ORDER_STATUS_TO_BE_DELIVERED &&
                order.getOrderStatus() != OrderConstant.ORDER_STATUS_TO_BE_RECEIVED &&
                order.getOrderStatus() != OrderConstant.ORDER_STATUS_ALREADY_RECEIVED) {
            return CommonResult.failed(CommonCodeEnum.ORDER_CAN_NOT_REFUND);
        }
        // 校验订单是否结束
        if (order.getIsClose()) {
            return CommonResult.failed(CommonCodeEnum.ORDER_IS_CLOSED);
        }
        // 校验订单是否有售后
        if (!order.getIsRefund()) {
            return CommonResult.failed(CommonCodeEnum.ORDER_IS_NOT_IN_REFUNDED);
        }
        // 查询不到支付订单号
        if (isNullOrEmpty(order.getPaymentTransactionId())) {
            return CommonResult.failed(CommonCodeEnum.ORDER_PAYMENT_TRANSACTION_ID_NOT_EXIST);
        }

        // 修改退款信息
        orderRefund.setStatus(OrderRefundConstant.ORDER_REFUND_STATUS_REFUNDING); // 退款中
        orderRefund.setProcessApproverId(userId); // 流程审批人id
        orderRefund.setProcessApprovalStatus(OrderRefundConstant.ORDER_REFUND_PROCESS_STATUS_PASS); // 审批状态: 通过
        if (!isNullOrEmpty(refundReq.getNotes())) {
            orderRefund.setNotes(refundReq.getNotes()); // 备注信息
        }
        boolean refundUpdSuccess = this.updateById(orderRefund);
        if (!refundUpdSuccess) { // 修改失败
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        // 支付金额为0
        if (order.getPaymentAmount().compareTo(BigDecimal.valueOf(0)) <= 0) {
            if (!order.getIsUsePoint()) {
                return CommonResult.failed(CommonCodeEnum.ORDER_CAN_NOT_REFUND);
            }

            // 退还积分
            if (order.getIsUsePoint() != null && order.getIsUsePoint()) {
                MmsConsumptionPointRecord pointRecord = mmsConsumptionPointRecordMapper.selectById(order.getPointRecordId());

                // 添加退还记录
                MmsConsumptionPointRecord backPointRecord = new MmsConsumptionPointRecord();
                BeanUtils.copyProperties(pointRecord, backPointRecord, "id");
                backPointRecord.setStatus(ConsumptionPointRecordConstant.POINT_RECORD_STATUS_INCREASE);
                mmsConsumptionPointRecordMapper.insert(backPointRecord);

                // 退还积分
                List<MmsUserConsumptionPoint> userPointList = mmsUserConsumptionPointMapper.selectList(new LambdaQueryWrapper<MmsUserConsumptionPoint>()
                        .eq(MmsUserConsumptionPoint::getUserId, order.getUserId()));
                MmsUserConsumptionPoint userPoint = userPointList.get(0);
                // 当前积分 = 原积分 + 退还积分
                userPoint.setPoints(userPoint.getPoints() + pointRecord.getPoints());
                mmsUserConsumptionPointMapper.updateById(userPoint);
            }

            // 修改退款记录
            Date nowDate = new Date(); // 当前时间
            orderRefund.setRefundAmount(new BigDecimal(0));
            orderRefund.setRefundTime(nowDate);
            orderRefund.setStatus(OrderRefundConstant.ORDER_REFUND_STATUS_REFUNDED); // 退货状态: 已退款
            boolean updSuccess = this.updateById(orderRefund);
            if (!updSuccess) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
            }

            // 修改订单包含药品信息
            MmsOrderMedicineInfo orderMedicineInfo = new MmsOrderMedicineInfo();
            orderMedicineInfo.setRefundId(orderRefund.getId());
            orderMedicineInfo.setType(OrderMedicineInfoConstant.ORDER_MEDICINE_INFO_REFUND);
            int orderMedicineInfoUpdNum = mmsOrderMedicineInfoMapper.update(orderMedicineInfo, new LambdaQueryWrapper<MmsOrderMedicineInfo>()
                    .eq(MmsOrderMedicineInfo::getOrderId, order.getId()));
            if (orderMedicineInfoUpdNum < 1) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
            }

            // 修改订单状态
            order.setIsRefunding(false); // 不在售后中
            order.setIsClose(OrderConstant.ORDER_IS_CLOSE_YES); // 订单结束
            order.setEndTime(nowDate); // 订单结束时间
            int orderUpdNum = mmsOrderMapper.updateById(order);
            if (orderUpdNum != 1) { // 修改失败
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
            }

        } else {
            // 发起预退款
            RefundReq preRefundReq = new RefundReq();
            preRefundReq.setTransaction_id(order.getPaymentTransactionId()); // 微信交易订单号
            preRefundReq.setOut_trade_no(order.getId()); // 商户订单号
            preRefundReq.setOut_refund_no(orderRefund.getId()); // 退款单号
            preRefundReq.setReason(OrderRefundConstant.ORDER_REFUND_REASON_USER_SUBMIT); // 退款原因: 用户申请退款
            // 设置订单金额 单位：分(订单金额 = 原金额(元) * 100)
            long total = order.getPaymentAmount().multiply(BigDecimal.valueOf(100)).longValue();
            preRefundReq.setTotal(total); // 订单金额 单位：分
            preRefundReq.setRefund(total); // 退款金额 单位：分(全部退)
            preRefundReq.setPaymentMethod(order.getPaymentMethod()); // 支付方式
            RefundResponse refund = paymentUtil.createRefund(preRefundReq);

            // 更新退款信息
            if (refund != null) {
                // 退还优惠券
                if (!isNullOrEmpty(order.getCouponInfo())) { // 存在优惠券信息
                    MmsUserCouponRelationResp couponInfo = JSONObject.parseObject(order.getCouponInfo(), MmsUserCouponRelationResp.class);
                    if (couponInfo != null) {
                        MmsUserCouponRelation userCoupon = mmsUserCouponRelationService.getById(couponInfo.getId());
                        if (userCoupon != null) {
                            // 优惠券状态修改为未使用
                            userCoupon.setIsUse(UserCouponRelationConstant.USER_COUPON_RELATION_NOT_USE);
                            boolean couponUpdSuccess = mmsUserCouponRelationService.updateById(userCoupon);
                            if (!couponUpdSuccess) { // 修改失败
                                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
                            }
                        }
                    }
                }

                // 退还积分
                if (order.getIsUsePoint() != null && order.getIsUsePoint()) {
                    MmsConsumptionPointRecord pointRecord = mmsConsumptionPointRecordMapper.selectById(order.getPointRecordId());

                    // 添加退还记录
                    MmsConsumptionPointRecord backPointRecord = new MmsConsumptionPointRecord();
                    BeanUtils.copyProperties(pointRecord, backPointRecord, "id");
                    backPointRecord.setStatus(ConsumptionPointRecordConstant.POINT_RECORD_STATUS_INCREASE);
                    mmsConsumptionPointRecordMapper.insert(backPointRecord);

                    // 退还积分
                    List<MmsUserConsumptionPoint> userPointList = mmsUserConsumptionPointMapper.selectList(new LambdaQueryWrapper<MmsUserConsumptionPoint>()
                            .eq(MmsUserConsumptionPoint::getUserId, order.getUserId()));
                    MmsUserConsumptionPoint userPoint = userPointList.get(0);
                    // 当前积分 = 原积分 + 退还积分
                    userPoint.setPoints(userPoint.getPoints() + pointRecord.getPoints());
                    mmsUserConsumptionPointMapper.updateById(userPoint);
                }

                // 修改退款记录
                orderRefund.setRefundId(refund.getRefundTradeId());
                orderRefund.setRefundAmount(centsToYuan(refund.getTotal()));
                orderRefund.setRefundTime(refund.getSuccessTime());
                orderRefund.setStatus(OrderRefundConstant.ORDER_REFUND_STATUS_REFUNDED); // 退货状态: 已退款
                boolean updSuccess = this.updateById(orderRefund);
                if (!updSuccess) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
                }

                // 修改订单包含药品信息
                MmsOrderMedicineInfo orderMedicineInfo = new MmsOrderMedicineInfo();
                orderMedicineInfo.setRefundId(orderRefund.getId());
                orderMedicineInfo.setType(OrderMedicineInfoConstant.ORDER_MEDICINE_INFO_REFUND);
                int orderMedicineInfoUpdNum = mmsOrderMedicineInfoMapper.update(orderMedicineInfo, new LambdaQueryWrapper<MmsOrderMedicineInfo>()
                        .eq(MmsOrderMedicineInfo::getOrderId, order.getId()));
                if (orderMedicineInfoUpdNum < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
                }

                // 修改订单状态
                Date nowDate = new Date(); // 当前时间
                order.setIsRefunding(false); // 不在售后中
                order.setIsClose(OrderConstant.ORDER_IS_CLOSE_YES); // 订单结束
                order.setEndTime(nowDate); // 订单结束时间
                int orderUpdNum = mmsOrderMapper.updateById(order);
                if (orderUpdNum != 1) { // 修改失败
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
                }
            }
        }

        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult refuseRefund(MmsOrderRefundReq refundReq, String userId) {
        if (isNullOrEmpty(refundReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        // 查询订单退款记录
        MmsOrderRefund orderRefund = this.getById(refundReq.getId());
        if (orderRefund == null) {
            return CommonResult.failed(CommonCodeEnum.ORDER_REFUND_NOT_EXIST);
        }
        // 非待退款状态不可拒绝退款
        if (orderRefund.getStatus() != OrderRefundConstant.ORDER_REFUND_STATUS_TO_BE_REFUNDED) {
            return CommonResult.failed(CommonCodeEnum.ORDER_CAN_NOT_REFUND);
        }

        // 查询订单数据
        MmsOrder order = mmsOrderMapper.selectById(orderRefund.getOrderId());
        if (order == null) { // 订单不存在
            return CommonResult.failed(CommonCodeEnum.ORDER_NOT_EXIST);
        }
        // 订单非 待发货、待收货、已收货 状态不可进行退款相关操作
        if (order.getOrderStatus() != OrderConstant.ORDER_STATUS_TO_BE_DELIVERED &&
                order.getOrderStatus() != OrderConstant.ORDER_STATUS_TO_BE_RECEIVED &&
                order.getOrderStatus() != OrderConstant.ORDER_STATUS_ALREADY_RECEIVED) {
            return CommonResult.failed(CommonCodeEnum.ORDER_CAN_NOT_REFUND);
        }
        // 校验订单是否结束
        if (order.getIsClose()) {
            return CommonResult.failed(CommonCodeEnum.ORDER_IS_CLOSED);
        }
        // 校验订单是否有售后
        if (!order.getIsRefund()) {
            return CommonResult.failed(CommonCodeEnum.ORDER_IS_NOT_IN_REFUNDED);
        }

        // 修改退款信息
        orderRefund.setStatus(OrderRefundConstant.ORDER_REFUND_STATUS_REFUNDED_FAIL); // 退款失败
        orderRefund.setProcessApprovalStatus(OrderRefundConstant.ORDER_REFUND_PROCESS_STATUS_REFUSE); // 审批状态: 拒绝
        if (!isNullOrEmpty(refundReq.getNotes())) {
            orderRefund.setNotes(refundReq.getNotes()); // 备注信息
        }
        boolean refundUpdSuccess = this.updateById(orderRefund);
        if (!refundUpdSuccess) { // 修改失败
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        // 更新订单状态
        order.setIsRefunding(false); // 不在售后中
        mmsOrderMapper.updateById(order);

        return CommonResult.success();
    }

    @Override
    public ResponseResult getAllRefund(Integer pageNum, Integer pageSize, String searchStr, Integer status) {
        LambdaQueryWrapper<MmsOrderRefund> queryWrapper = new LambdaQueryWrapper<MmsOrderRefund>()
                .orderByDesc(MmsOrderRefund::getCreateTime);

        // 搜索字符串
        if (!isNullOrEmpty(searchStr)) {
            //删除空白格
            StringUtils.deleteWhitespace(searchStr);

            List<MmsOrder> orderList = mmsOrderMapper.selectList(new LambdaQueryWrapper<MmsOrder>()
                    .like(MmsOrder::getAddressInfo, searchStr).or() // 配送地址信息
                    .like(MmsOrder::getNotes, searchStr)); // 订单备注信息
            List<String> orderIdList = orderList.stream().map(MmsOrder::getId).distinct().collect(Collectors.toList());

            List<MmsUser> userList = mmsUserMapper.selectList(new LambdaQueryWrapper<MmsUser>()
                    .like(MmsUser::getTel, searchStr).or() // 用户电话号码
                    .like(MmsUser::getUsername, searchStr).or() // 用户昵称
                    .like(MmsUser::getNickName, searchStr)); // 用户昵称
            List<String> userIdList = userList.stream().map(MmsUser::getId).distinct().collect(Collectors.toList());

            queryWrapper.and(i -> i.like(MmsOrderRefund::getMedicineInfo, searchStr).or() // 药品信息
                    .like(MmsOrderRefund::getReason, searchStr).or() // 退款原因
                    .like(MmsOrderRefund::getNotes, searchStr).or() // 备注信息
                    .in(!orderIdList.isEmpty(), MmsOrderRefund::getOrderId, orderIdList).or()
                    .in(!userIdList.isEmpty(), MmsOrderRefund::getUserId, userIdList));
        }

        //退款审批状态: 0.待审批 1.通过 2.拒绝
        if (!isNullOrEmpty(status)) {
            if (OrderRefundConstant.ORDER_REFUND_PROCESS_STATUS_LIST.contains(status)) {
                queryWrapper.eq(MmsOrderRefund::getProcessApprovalStatus, status);
            }
        }

        Page<MmsOrderRefund> page = new Page<>(pageNum, pageSize);
        this.page(page, queryWrapper);
        List<MmsOrderRefundResp> orderRefundRespList = page.getRecords().stream().map(orderRefund -> {
            MmsOrderRefundResp orderRefundResp = new MmsOrderRefundResp();
            BeanUtils.copyProperties(orderRefund, orderRefundResp);

            MmsUser user = mmsUserMapper.selectById(orderRefund.getUserId());
            if (user != null) {
                MmsUserResp userResp = new MmsUserResp();
                BeanUtils.copyProperties(user, userResp);
                orderRefundResp.setUserInfo(userResp);
            }

            MmsUser approver = mmsUserMapper.selectById(orderRefund.getProcessApproverId());
            if (approver != null) {
                MmsUserResp userResp = new MmsUserResp();
                BeanUtils.copyProperties(approver, userResp);
                orderRefundResp.setApproverInfo(userResp);
            }

            MmsOrder order = mmsOrderMapper.selectById(orderRefund.getOrderId());
            MmsOrderResp orderResp = new MmsOrderResp();
            BeanUtils.copyProperties(order, orderResp);
            orderResp.setMedicineInfo(JSON.parseArray(order.getMedicineInfo(), OrderMedicineInfoResp.class)); // 药品信息
            orderResp.setAddressInfo(JSON.parseObject(order.getAddressInfo(), MmsAddresses.class)); // 配送地址信息
            if (order.getCouponInfo() != null) {
                orderResp.setCouponInfo(JSON.parseObject(order.getCouponInfo(), MmsUserCouponRelationResp.class)); // 优惠信息
            }
            orderRefundResp.setOrderInfo(orderResp);

            return orderRefundResp;
        }).collect(Collectors.toList());

        return CommonResult.success(orderRefundRespList, (int) page.getTotal());
    }

    @Override
    public ResponseResult getRefundDetail(String refundId) {
        MmsOrderRefund orderRefund = this.getById(refundId);
        if (orderRefund == null) {
            return CommonResult.failed(CommonCodeEnum.ORDER_REFUND_NOT_EXIST);
        }

        MmsOrderRefundResp orderRefundResp = new MmsOrderRefundResp();
        BeanUtils.copyProperties(orderRefund, orderRefundResp);
        MmsUser user = mmsUserMapper.selectById(orderRefund.getUserId());
        if (user != null) {
            MmsUserResp userResp = new MmsUserResp();
            BeanUtils.copyProperties(user, userResp);
            orderRefundResp.setUserInfo(userResp);
        }

        MmsUser approver = mmsUserMapper.selectById(orderRefund.getProcessApproverId());
        if (approver != null) {
            MmsUserResp userResp = new MmsUserResp();
            BeanUtils.copyProperties(approver, userResp);
            orderRefundResp.setApproverInfo(userResp);
        }

        MmsOrder order = mmsOrderMapper.selectById(orderRefund.getOrderId());
        MmsOrderResp orderResp = new MmsOrderResp();
        BeanUtils.copyProperties(order, orderResp);
        orderResp.setMedicineInfo(JSON.parseArray(order.getMedicineInfo(), OrderMedicineInfoResp.class)); // 药品信息
        orderResp.setAddressInfo(JSON.parseObject(order.getAddressInfo(), MmsAddresses.class)); // 配送地址信息
        if (order.getCouponInfo() != null) {
            orderResp.setCouponInfo(JSON.parseObject(order.getCouponInfo(), MmsUserCouponRelationResp.class)); // 优惠信息
        }
        orderRefundResp.setOrderInfo(orderResp);

        return CommonResult.success(orderRefundResp);
    }

    /**
     * 将以分为单位的金额(Integer)转换为以元为单位的金额(BigDecimal)
     *
     * @param moneyInCents 以分为单位的金额(Integer)
     * @return 以元为单位的金额(BigDecimal)
     */
    private BigDecimal centsToYuan(Integer moneyInCents) {
        // 将分转换为元, 需要除以100, 并将结果存储为BigDecimal类型
        return new BigDecimal(moneyInCents).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
    }
}
